package com.example.demo.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 文件上传工具包
 */
public class FileUtil {
    /**
     * @param file     文件
     * @param path     文件存放路径
     * @param fileName 源文件名
     * @return
     */
    public static boolean uploadImage(MultipartFile file, String path, String fileName) {
        //获取文件名
        String originalFileName = file.getOriginalFilename();
        String typeName = originalFileName.substring(originalFileName.indexOf(".") + 1);

        // 生成新的文件名
        if (fileName == null) {
            fileName = originalFileName;
        }

        String realPath = path + File.separator + fileName;
        File targetFile = new File(realPath);

        //判断文件父目录是否存在
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdir();
        }

        InputStream inputStream;
        OutputStream outputStream;
        try {
            //保存文件
//            file.transferTo(targetFile);

            inputStream = file.getInputStream();
            outputStream = new FileOutputStream(targetFile);
            //添加水印
            WaterMarkUtil.markImageByIO("水印测试", inputStream, outputStream, typeName, 0);
            outputStream.close();
            inputStream.close();
            return true;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
}
